/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: RabbitProducer.java
 * Author:   cakin
 * Date:     2020/5/2
 * Description: 生产者
 */
package com.rabbitmq.durable;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.common.Constant.NUM2;

/**
 * 持久化测试
 */
@Slf4j
public class DurableTest {
    /**
     * 交换器
     */
    private static final String EXCHANGE_NAME = "exchange_durable";
    /**
     * 绑定键
     */
    private static final String ROUTING_KEY = "routingkey_durable";
    /**
     * 队列
     */
    private static final String QUEUE_NAME = "queue_durable";
    public static void main( String[] args ) {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();
            // 通过durable控制交换器是否持久化，如果设置为false，RabbitMQ重启后，该交换器消失
            channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
            // 通过durable控制队列是否持久化，如果设置为false，RabbitMQ重启后，该队列消失，队列中的消息也会丢失
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
            // 通过设置deliveryMode是否为2，控制消息是否会持久化，如果设置为非2，RabbitMQ重启后，队列中的消息也丢失
            AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
            builder.deliveryMode(1);
            AMQP.BasicProperties properties = builder.build();
            String message = "Hello World !";
            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY,
                    properties,
                    message.getBytes());
            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}
